package com.logicwin.aibala.ui.screens.Search;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;


import com.logicwin.aibala.R;
import com.logicwin.aibala.model.androidSWInfo.APKListItem;
import com.logicwin.aibala.model.androidSWInfo.AndroidSWInfoService;
import com.logicwin.aibala.ui.screens.Screen;
import com.logicwin.aibala.ui.screens.screenmain.ApkPackageAdapter;
public class ScreenSearch extends Screen implements Runnable {
	
	static String TAG = ScreenSearch.class.getCanonicalName();

	private PopupWindow mPopupWindow = null;
	private Thread mThread;
	private boolean mRunning = true;
	private SearchView mSearchView;
	private LinearLayout mSearchViewLayout;
	private LinearLayout mSearchNavigateLayout;
	private Button	mSearchButton;
	private EditText mSearchText;
	private ApkPackageAdapter m_SearchResultAdapter = null;
	public ScreenSearch() {
		super(SCREEN_TYPE.SEARCH_T, ScreenSearch.class.getCanonicalName());
		// TODO Auto-generated constructor stub
	}
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_search); 
		mSearchView = (SearchView)this.findViewById(R.id.search_view);
		
		mSearchViewLayout = (LinearLayout)this.findViewById(R.id.search_view_layout);
		Log.i("ScreenSearch::onCreate", "width "+mSearchView.getWidth()+",height "+mSearchView.getHeight());
		Log.i("ScreenSearch::onCreate", "width "+mSearchViewLayout.getWidth()+",height "+mSearchViewLayout.getHeight());
		mSearchNavigateLayout = (LinearLayout) this.findViewById(R.id.search_top_layout);
		mSearchText = (EditText) this.findViewById(R.id.search_text);
		mSearchButton = (Button) this.findViewById(R.id.search_button);
		mSearchButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				if(imm.isActive()){					
					imm.hideSoftInputFromInputMethod(mSearchText.getApplicationWindowToken(), 
							InputMethodManager.HIDE_IMPLICIT_ONLY|InputMethodManager.HIDE_NOT_ALWAYS);
					/*
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); */
				}
				String text = mSearchText.getText().toString();
				Log.i("ScreenSearch",text+text.length());
				mSearchText.clearFocus();
				if(text.length()<1) return;
				PopDialog(text);
			} });
	}	
	public boolean onTouchEvent(MotionEvent event) {
		Log.i(TAG, "ScreenSearch::onTouchEvent is catched.");
		//if(mMoveStop == false)	return true;
		
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			float xPos = event.getX();
			float yPos = event.getY() - mSearchNavigateLayout.getHeight();
			String word = mSearchView.HitScreen(xPos, yPos);
			Log.i("ScreenSearch","word is "+ word);
			if(word == null) return false;
			//弹出对话框
			try{
			PopDialog(word);
			}
			catch(Exception e){
				Log.e("ScreenSearch","popDialog error: " +e.getMessage());
			}
			return true;
		case MotionEvent.ACTION_UP:

			return true;

		}
		return super.onTouchEvent(event);
	}
    public void run() {  
        while (mRunning) {  
            try {              	
            	Thread.sleep(100); 
            	mSearchView.postInvalidate();
	            
            } catch (InterruptedException e) {  
                Thread.currentThread().interrupt();  
            }    
        }  
    } 	
    public void onStart(){    	
		mThread = new Thread(this); 		
		mThread.start();
		Log.v(TAG, "onStart()");  
		super.onStart();
    }
    public void onResume(){
    	mRunning = true;
    	super.onResume();
    }
    public void onPause(){
    	if(mPopupWindow != null){
    		mPopupWindow.dismiss();
    		mPopupWindow = null;
    	}
    	mRunning = false;
    	super.onPause();
    }
    private void refreshListView(String filter){
    	if(m_SearchResultAdapter != null){
    		Log.i("refreshlistview","refreshlistview "+filter);
    		
			List<APKListItem> searchResult = AndroidSWInfoService.getSearchResult(filter);
			if(searchResult == null){				
				PopAlertDialog();
				mPopupWindow = null;
				return;
			}
			m_SearchResultAdapter.setCurrApkList(searchResult, "search", "search");
			m_SearchResultAdapter.notifyDataSetChanged();
    	}
    }
    private void PopAlertDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this); 
		builder.setMessage("没有找到匹配内容") 
		       .setCancelable(false) 
		       .setPositiveButton("确定", new DialogInterface.OnClickListener() { 
		           public void onClick(DialogInterface dialog, int id) { 
		        	   dialog.cancel();  
		           } 
		       }) 
		       ; 
		builder.create().show();     	
    }
	public boolean haveMenu() {
		return true;
	}    
	private void PopDialog(String filter){
		if(mPopupWindow == null)
		{
			//Context mContext = ScreenSearch.this;
			LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View search_popwindwow = mLayoutInflater.inflate(
					R.layout.search_dialog, null);
			mPopupWindow = new PopupWindow(search_popwindwow,
					LayoutParams.FILL_PARENT, /*LayoutParams.WRAP_CONTENT*/mSearchView.getHeight()
					+mSearchNavigateLayout.getHeight());
			
			ListView searchResultList = (ListView)search_popwindwow.findViewById(R.id.searchResult);
			
			List<APKListItem> searchResult = AndroidSWInfoService.getSearchResult(filter);
			if(searchResult == null){				
				PopAlertDialog();
				mPopupWindow = null;
				return;
			}
			m_SearchResultAdapter = new ApkPackageAdapter(this,searchResult,"search","search");
			searchResultList.setAdapter(m_SearchResultAdapter);		
			searchResultList.setOnItemClickListener(m_SearchResultAdapter);
		}
		
		EditText text_view = (EditText)mPopupWindow.getContentView().findViewById(R.id.search_dialog_text);
		text_view.setText(filter);
		text_view.setSelection(filter.length());  

		Button searchButton = (Button)mPopupWindow.getContentView().findViewById(R.id.search_dialog_button);
		searchButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EditText text_view = (EditText)mPopupWindow.getContentView().findViewById(R.id.search_dialog_text);
				String text = text_view.getText().toString();
				if(text.length()<1) return;
				
				refreshListView(text);
			}			
		});
		//设置整个popupwindow的样式。           
		//mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_corners_pop)); 
		//使窗口里面的空间显示其相应的效果，比较点击button时背景颜色改变。           
		//如果为false点击相关的空间表面上没有反应，但事件是可以监听到的。            
		//listview的话就没有了作用。      
		mPopupWindow.update(); 
		mPopupWindow.setFocusable(true);            				
		mPopupWindow.setTouchable(true);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		
		//mPopupWindow.showAtLocation(findViewById(R.id.search_top_layout), Gravity.NO_GRAVITY, 0, 0);
		mPopupWindow.showAsDropDown(findViewById(R.id.search_view),0,-mSearchView.getHeight());
		
	}
}
